<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading" :disabled="formType === 'detail'">
      <el-form-item label="作品名称：" :prop="formType === 'detail' ? '' : 'workName'">
        <span v-if="formType === 'detail'">{{ formData.workName }}</span>
        <el-input v-model="formData.workName" placeholder="请输入作品名称"  v-if="formType !== 'detail'" />
      </el-form-item>
      <el-form-item label="英文名称：" :prop="formType === 'detail' ? '' : 'workEngName'" >
        <span v-if="formType === 'detail'">{{ formData.workEngName }}</span>
        <el-input v-model="formData.workEngName" placeholder="请输入英文作品名称"  v-if="formType !== 'detail'" />
      </el-form-item>
      <el-form-item label="作品分类：" :prop="formType === 'detail' ? '' : 'categoryId'">
        <!--查看详情展示的信息-->
        <span v-if="formType === 'detail'">{{ getCategoryName(formData.parentId || 0, formData.categoryId || 0) }}</span>
        <el-select v-model="oneWorkCategoryId" placeholder="请选择一级分类" @change="changeOneCategory" style="width: 140px;" v-if="formType !== 'detail'">
          <el-option v-for="item in oneCategories" :key="item.id" :label="item.categoryName" :value="item.id" />
        </el-select>

        <el-select v-model="twoWorkCategoryId" placeholder="请选择二级分类" style="width: 140px;" @change="changeTwoCategory" v-if="formType !== 'detail'">
          <el-option v-for="item in twoCategories" :key="item.id" :label="item.categoryName" :value="item.id" />
        </el-select>
        <!-- <el-input v-model="formData.catagoryId" placeholder="请输入分类编号" /> -->
      </el-form-item>

      <el-form-item label="作品类型：" :prop="formType === 'detail' ? '' : 'workType'" >
        <!-- 如果是查看详情模式，显示类型标签 -->
        <span v-if="formType === 'detail'">{{ getTypeLabel(formData.workType ?? 0) }}</span>
        <el-select v-model="formData.workType" placeholder="请选择作品类型" v-if="formType !== 'detail'">
          <el-option  v-for="dict in getIntDictOptions(DICT_TYPE.TD_WORK_TYPE)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="作者：" prop="nickName" v-if="formType === 'detail'">
        <span>{{ formData.nickName }}</span>
      </el-form-item>

      <el-form-item label="封面：" :prop="formType === 'detail' ? '' : 'imgSrc'" >
        <UploadImg v-model="formData.imgSrc" :is-detail="formType === 'detail'" />
      </el-form-item>
      <el-form-item
        v-if="(formType === 'detail' && formData.exhibitionImage) || formType!== 'detail'"
        label="个人展览图："
        :prop="formType === 'detail'? '' : 'exhibition_image'"
       >
      <UploadImg v-model="formData.exhibitionImage" :is-detail="formType === 'detail'" />
    </el-form-item>
    <!-- vr展厅图表单项 -->
    <!-- <el-form-item
      v-if="(formType === 'detail' && formData.vrImage) || formType!== 'detail'"
      label="vr展厅图: "
      :prop="formType === 'detail'? '' : 'vr_image'"
    >
      <UploadImg v-model="formData.vrImage" :is-detail="formType === 'detail'" />
    </el-form-item> -->

      <!--如果是查看详情时，不显示文件地址-->
      <el-form-item label="文件地址" prop="filepath"  v-if="formType !== 'detail'">
        <UploadFile v-model="formData.filepath" />
      </el-form-item>

      <el-form-item label="介绍：" :prop="formType === 'detail' ? '' : 'description'">
         <!-- 如果是查看详情模式 -->
          <span v-if="formType === 'detail'">
         <!-- 如果描述为空，显示默认值“无” -->
          <span v-if="!formData.description" >无</span>
         <!-- 否则渲染 HTML 内容 -->
          <span v-else v-html="formData.description"></span>
         </span>
        <!-- 如果是编辑/新增模式 -->
        <Editor v-else v-model="formData.description" height="150px" />
      </el-form-item>

       <!-- 动态生成的表格 -->
       <el-form-item label="作品集与说明" v-if="!isImageViewerOpen && formType === 'detail'" >
        <el-table :data="imageDescriptions" border style="width: 100%">
          <!-- 图片列 -->
          <el-table-column prop="imgSrc" label="图片" width="200">
            <template #default="{ row }">
              <el-image
                v-if="row.imgSrc"
                :src="row.imgSrc"
                fit="cover"
                style="width: 100px; height: 100px"
                :preview-src-list="[row.imgSrc]"
                :initial-index="0"
                :preview-closeable="false"
                @click="openImageViewer(row.imgSrc)"
              />
              <span v-else>无图片</span>
            </template>
          </el-table-column>
          <!-- 说明列 -->
          <el-table-column prop="describes" label="说明">
            <template #default="{ row }">
              <!-- <span >{{ row.describes || '无说明' }}</span> -->
              <div class="description-container" v-html="row.describes || '无说明'"></div>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
        <!-- 图片预览组件 -->
    <el-image-viewer
      v-if="isImageViewerOpen"
      :url-list="[currentImgSrc]"
      :on-close="closeImageViewer"
      :z-index="9999"
      :initial-index="0"
      hide-on-click-modal
      @close="closeImageViewer"
    />
    </el-form>
    <template #footer>
      <!-- 确定/取消按钮 如果是查看详情时不显示确定按钮 -->
  <el-button v-if="formType !== 'detail'" @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
  <!-- 只有在查看详情且状态为未审核(status=1)时才显示审核按钮 -->
  <template v-if="formType === 'detail' && Number(formData.status) === 1">
    <el-button @click="formData.id ? handleAudit(formData.id, formData.published === true ? 3 : 2) : null" type="success">通 过</el-button>
    <el-button @click="formData.id ? handleAudit(formData.id, 4) : null" type="danger">驳 回</el-button>
  </template>
  <el-button @click="dialogVisible = false">取 消</el-button>
</template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { WorkApi, WorkVO } from '@/api/td/work'
import { WorksCatagoryApi, WorksCatagoryTreeVO, } from '@/api/td/workscatagory'
// import { fromType } from 'vue-types'
import { UploadImg } from '@/components/UploadFile'
import { ref } from 'vue';
/** 作品 表单 */
defineOptions({ name: 'WorkForm' })

// 动态生成的表格数据
const imageDescriptions = ref<any[]>([])
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  workName: undefined,
  categoryId: undefined,
  imgSrc: undefined,
  // imgSrcs: [] as string[], // 修改为数组类型
  workType: undefined,
  filepath: undefined,
  description: undefined,
  parentId: undefined,
  describes: undefined,
  nickName: undefined,
  exhibitionImage: undefined,
  vrImage: undefined,
  workEngName: undefined,
  published: undefined,
  status: undefined,
})
const formRules = reactive({
  workName: [{ required: true, message: '作品名称不能为空', trigger: 'blur' }],
  catagoryId: [{ required: true, message: '分类编号不能为空', trigger: 'blur' }],
  imgSrc: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
  workType: [{ required: true, message: '作品类型不能为空', trigger: 'change' }],
  description: [{ required: true, message: '介绍不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
//const workCategory = ref<WorksCatagoryVO>()



/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  
  resetForm()
  // 修改时，设置数据
  if (id){
    formLoading.value = true
    try {
      formData.value = await WorkApi.getWork(id)
      oneWorkCategoryId.value = formData.value.parentId // 获取一级分类ID
      twoWorkCategoryId.value = formData.value.categoryId // 获取二级分类ID
       // 加载二级分类数据
       if (oneWorkCategoryId.value !== undefined) {
        await changeOneCategory(oneWorkCategoryId.value)
      }
      // 调用后端接口获取图片与说明数据
      const imagesAndDescriptions = await WorkApi.getImagesAndDescriptions(id)
      imageDescriptions.value = imagesAndDescriptions.map(item => ({
        imgSrc: item.imgSrc || '', // 如果图片路径为空，则设置为空字符串
        describes: item.describes || '', // 如果说明为空，则设置为空字符串
      }))
       
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as WorkVO
    if (formType.value === 'create') {
      await WorkApi.createWork(data)
      message.success(t('common.createSuccess'))
    } else {
      await WorkApi.updateWork(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    workName: undefined,
    categoryId: undefined,
    imgSrc: undefined,
    workType: undefined,
    filepath:undefined,
    description: undefined,
    parentId: undefined,
    describes: undefined,
    nickName: undefined,
    exhibitionImage: undefined,
    vrImage: undefined,
    workEngName: undefined,
    published: undefined,
    status: undefined,
  }
  // 新增时避免携带其他数据
  oneWorkCategoryId.value = undefined
  twoWorkCategoryId.value = undefined
  twoCategories.value = []
  formRef.value?.resetFields()
}

const oneWorkCategoryId = ref(undefined)
const twoWorkCategoryId = ref(undefined)

const oneCategories = ref<WorksCatagoryTreeVO[]>([]) // 一级分类
const twoCategories = ref<WorksCatagoryTreeVO[]>([]) //二级分类
const getCategoryList = async (parentId: number) => {

  try {
    const data = await WorksCatagoryApi.getListByParentId(parentId)
    oneCategories.value = data

  } finally {

  }
}

const changeOneCategory = async (id: number) => {
  if (id === null) return

  const data = await WorksCatagoryApi.getListByParentId(id)
  twoCategories.value = data

}
const changeTwoCategory = async (id)=>{

  formData.value.categoryId = id
}

onMounted(() => {
  getCategoryList(0)
})


/**
 * 获取分类名称的辅助方法
 * 根据 parentId 和 categoryId 查找对应的分类名称
 */
 const getCategoryName = (parentId: number, categoryId: number): string => {
  const parentCategory = oneCategories.value.find(item => item.id === parentId)
  const childCategory = twoCategories.value.find(item => item.id === categoryId)
  return `${parentCategory?.categoryName || ''} / ${childCategory?.categoryName || ''}`
}
/**
 * 获取类型标签的辅助方法
 * 根据 workType 查找对应类型的标签
 */
 const getTypeLabel = (type: number): string => {
  const dict = getIntDictOptions(DICT_TYPE.TD_WORK_TYPE).find(item => item.value === type)
  return dict?.label || ''
}



// 控制表格和图片预览的显示状态
const isImageViewerOpen = ref(false);
const currentImgSrc = ref('');

// 打开图片预览
const openImageViewer = (imgSrc: string) => {
  currentImgSrc.value = imgSrc;
  isImageViewerOpen.value = true;
};

// 关闭图片预览
const closeImageViewer = () => {
  isImageViewerOpen.value = false;
};

// 处理审核
const handleAudit = async (id: number, status: number) => {
  try {
    await WorkApi.updateWorkStatus(id, status)
    message.success('操作成功')
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    message.error('操作失败')
  }
}
</script>

<style>
.description-container p {
  margin: 0; /* 去掉 <p> 标签的默认外边距 */
  padding: 0; /* 去掉 <p> 标签的默认内边距 */
}
</style>